package com.ims.common.utils.file;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PDFUtil {
    private static final Logger log = LoggerFactory.getLogger(PDFUtil.class);
    /**
     * 使用pdfbox将整个pdf转换成图片
     *
     * @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
     * @param filename    PDF文件名不带后缀名
     * @param type        图片类型 png 和jpg
     */
    public static void pdf2png(String fileAddress, String filename, String type) {
        long startTime = System.currentTimeMillis();
        // 将文件地址和文件名拼接成路径 注意：线上环境不能使用\\拼接
        File file = new File(fileAddress + "\\" + filename + ".pdf");
        try {
            // 写入文件
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                // dpi为144，越高越清晰，转换越慢 // Windows native DPI
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                // 创建图像缓冲区
                Graphics2D g2d = (Graphics2D) image.getGraphics();

                // 设置水印文字
                String watermarkText = "样张";
                //设置水印文字的旋转角度
                Integer degree = -35;
                Font font = new Font("微软雅黑", Font.PLAIN, 40);
                g2d.setFont(font);
                g2d.setColor(new Color(255, 0, 0));
                // 设置边框粗细

//                Stroke originalStroke = g2d.getStroke();
//                Stroke borderStroke = new BasicStroke(4, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
//                g2d.setStroke(borderStroke);

                //设置水印旋转
                g2d.rotate(Math.toRadians(degree),(double)image.getWidth(),(double)image.getHeight());

                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
                g2d.setComposite(alpha);
                // 计算文字长度
                FontMetrics metrics = g2d.getFontMetrics(font);
                Rectangle2D textRect = metrics.getStringBounds(watermarkText, g2d);

                // 绘制水印
                g2d.drawString(watermarkText, (float) ((image.getWidth() - textRect.getWidth()) + 40), (int) ((image.getHeight() - textRect.getHeight())  - 120));



                // 释放图形上下文
                g2d.dispose();

                // 将图片写出到该路径下
                ImageIO.write(image, type, new File(fileAddress + "\\" + filename + "_" + (i + 1) + "." + type));
            }
            long endTime = System.currentTimeMillis();
            // //转化用时
            log.error("共耗时：" + ((endTime - startTime) / 1000.0) + "秒");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        pdf2png("C:\\Dev\\IMS\\uploadPath\\invoice", "2", "png");
    }
}
